package com.geo.auth.service;

import cn.dev33.satoken.stp.StpInterface;
import com.geo.auth.entity.Permission;
import com.geo.auth.entity.Role;
import com.geo.auth.mapper.PermissionMapper;
import com.geo.auth.mapper.RoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义Sa-Token权限验证接口实现
 * 
 * @author GEO Team
 * @version 1.0
 */
@Slf4j
@Component
public class StpInterfaceImpl implements StpInterface {
    
    private static final Logger log = LoggerFactory.getLogger(StpInterfaceImpl.class);
    
    @Autowired
    private RoleMapper roleMapper;
    
    @Autowired
    private PermissionMapper permissionMapper;
    
    /**
     * 返回指定账号id所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        try {
            String userId = String.valueOf(loginId);
            
            // 获取用户的所有权限
            List<Permission> permissions = permissionMapper.selectPermissionsByUserId(userId);
            
            List<String> permissionCodes = permissions.stream()
                    .filter(Permission::isAvailable)
                    .map(Permission::getPermissionCode)
                    .collect(Collectors.toList());
            
            log.debug("用户[{}]的权限列表: {}", userId, permissionCodes);
            
            return permissionCodes;
            
        } catch (Exception e) {
            log.error("获取用户权限列表失败", e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 返回指定账号id所拥有的角色标识集合
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        try {
            String userId = String.valueOf(loginId);
            
            // 获取用户的所有角色
            List<Role> roles = roleMapper.selectRolesByUserId(userId);
            
            List<String> roleCodes = roles.stream()
                    .filter(Role::isAvailable)
                    .map(Role::getRoleCode)
                    .collect(Collectors.toList());
            
            log.debug("用户[{}]的角色列表: {}", userId, roleCodes);
            
            return roleCodes;
            
        } catch (Exception e) {
            log.error("获取用户角色列表失败", e);
            return new ArrayList<>();
        }
    }
}